package com.msb.mall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.msb.common.dto.es.SkuESModel;
import com.msb.mall.search.config.MallElasticSearchConfiguration;
import com.msb.mall.search.constant.ESConstant;
import com.msb.mall.search.entity.vo.SearchParam;
import com.msb.mall.search.entity.vo.SearchResult;
import com.msb.mall.search.service.SearchService;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SearchServiceImpl implements SearchService {
    @Autowired
    private RestHighLevelClient client;

    /**
     * 检索处理
     * @param searchParam
     * @return
     */
    @Override
    public SearchResult search(SearchParam searchParam) {

        //1、准备检索的请求
        SearchRequest request = buildSearchRequest(searchParam);
        //2、执行检索操作
        SearchResult result = null;
        try {
            SearchResponse response = client.search(request, MallElasticSearchConfiguration.COMMON_OPTIONS);
            //3、把检索的结果封装问为SearchResult
            result = buildSearchResponse(response,searchParam);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return result;
    }
    /**
     * 根据检索的结构解析封装为SearchResult对象
     */
    private SearchResult buildSearchResponse(SearchResponse response, SearchParam searchParam) {
        System.out.println("response = " + response);
        SearchResult searchResult = new SearchResult();
        SearchHits hits = response.getHits();
        //1、检索的商品信息
        SearchHit[] products = hits.getHits();
        List<SkuESModel> product = new ArrayList<>();
        if(products != null){
            for (SearchHit searchHit :products) {
                String score = searchHit.getSourceAsString();
                //把json格式的字符串转为SkuESModel
                SkuESModel skuESModel = JSON.parseObject(score, SkuESModel.class);
                if(StringUtils.isNotEmpty(searchParam.getKeyword())){
                    HighlightField subTitle = searchHit.getHighlightFields().get("subTitle");
                    String highlightSubTitle = subTitle.getFragments()[0].string();
                    skuESModel.setSubTitle(highlightSubTitle);

                }
                product.add(skuESModel);
            }

        }
        searchResult.setProducts(product);
        Aggregations aggregations = response.getAggregations();
        //2、当前商品所涉及到的所有的品牌信息
        List<SearchResult.BrandVo>   brandVos = new ArrayList<>();
        ParsedLongTerms brandAgg = aggregations.get("brand_agg");
        List<? extends Terms.Bucket> buckets = brandAgg.getBuckets();
        if(buckets != null && !buckets.isEmpty()){
            for (Terms.Bucket bucket :buckets) {
                SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
                String keyAsString = bucket.getKeyAsString();
                //设置品牌的编号
                brandVo.setBrandId(Long.parseLong(keyAsString));
                //需要获取品牌的名称和图片
                getBrandToTerms(bucket, brandVo,"brand_name_agg");
                getBrandToTerms(bucket, brandVo, "brand_img_agg");
                brandVos.add(brandVo);
            }

        }
        searchResult.setBrands(brandVos);
        //3、当前商品涉及到的所有类别信息
        List<SearchResult.CateLogVo>   cateLogVos = new ArrayList<>();
        ParsedLongTerms catalogAgg = aggregations.get("catalog_agg");
        List<? extends Terms.Bucket> bucketsCatalogAgg = catalogAgg.getBuckets();
        if(bucketsCatalogAgg != null && !bucketsCatalogAgg.isEmpty()){
            for (Terms.Bucket bucket :bucketsCatalogAgg) {
                SearchResult.CateLogVo cateLogVo = new SearchResult.CateLogVo();
                //获取类别编号
                String keyAsString = bucket.getKeyAsString();
                cateLogVo.setCateLogId(Long.parseLong(keyAsString));
                ParsedStringTerms catalogNameAgg = bucket.getAggregations().get("catalog_name_agg");
                cateLogVo.setCateLogName(catalogNameAgg.getBuckets().get(0).getKeyAsString());
                cateLogVos.add(cateLogVo);
            }

        }
        searchResult.setCateLogs(cateLogVos);
        //4、当前商品涉及到的所有属性信息
        List<SearchResult.AttrVo>  attrs = new ArrayList<>();
        ParsedNested attrAgg = aggregations.get("attr_agg");
        ParsedLongTerms attrIdAgg = attrAgg.getAggregations().get("attr_id_agg");
        List<? extends Terms.Bucket> bucketsAttr = attrIdAgg.getBuckets();
        if(bucketsAttr != null && !bucketsAttr.isEmpty()){
            for (Terms.Bucket bucket :bucketsAttr) {
                SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
                String keyAsString = bucket.getKeyAsString();
                attrVo.setAttrId(Long.parseLong(keyAsString));
                //分別获取名称属性值
                getAttrToTerms( bucket, attrVo,"attr_name_agg");
                getAttrToTerms( bucket , attrVo,"attr_value_agg");
                attrs.add(attrVo);
            }

        }
        searchResult.setAttrs(attrs);
        //5、分页信息 、当前页，总记录数，总页数
        long total = hits.getTotalHits().value;
        searchResult.setTotal(total);
        searchResult.setPageNum(searchParam.getPageNum());
        long totalPage = total % ESConstant.PRODUCT_PAGE_SIZE == 0 ? total / ESConstant.PRODUCT_PAGE_SIZE : (total / ESConstant.PRODUCT_PAGE_SIZE) + 1;
        searchResult.setTotalPage((int) totalPage);
        List<Integer> navs = new ArrayList<>();
        for (int i = 1; i < totalPage; i++) {
            navs.add(i);
        }
        searchResult.setNavs(navs);
        return searchResult;
    }

    /**
     * 获取检索到的属性名称和值
     * @param bucket
     * @param attrVo
     * @param aggName
     */
    private void  getAttrToTerms(Terms.Bucket bucket,SearchResult.AttrVo attrVo,String aggName) {
        ParsedStringTerms brandNameAgg = bucket.getAggregations().get(aggName);
        if(brandNameAgg != null){
            List<? extends Terms.Bucket> buckets1 = brandNameAgg.getBuckets();
            if("attr_name_agg".equals(aggName)){
                attrVo.setAttrName(buckets1.get(0).getKeyAsString());
            }
            if("attr_value_agg".equals(aggName)){
                if(buckets1 != null && !buckets1.isEmpty()){
                    attrVo.setAttrValue(buckets1.stream().map(MultiBucketsAggregation.Bucket::getKeyAsString).collect(Collectors.toList()));
                }
            }
        }

    }
    /**
     * 获取检索到的商品图片和名称
     * @param bucket
     * @param brandVo
     * @param aggName
     */
    private void  getBrandToTerms(Terms.Bucket bucket,SearchResult.BrandVo brandVo,String aggName) {
        ParsedStringTerms brandNameAgg = bucket.getAggregations().get(aggName);
        List<? extends Terms.Bucket> buckets1 = brandNameAgg.getBuckets();
        if(buckets1 != null && !buckets1.isEmpty()){
            for (Terms.Bucket bucket1 :buckets1) {
                if("brand_name_agg".equals(aggName)){
                    brandVo.setBrandName(bucket1.getKeyAsString());
                }
                if("brand_img_agg".equals(aggName)){
                    brandVo.setBrandImg(bucket1.getKeyAsString());
                }
            }
        }
    }

    /**
     * 构建检索请求
     *模糊查询 ，关键字
     * 过滤（类别 品牌 属性 价格区间 库存 ）
     * 排序
     * 分页
     * 高亮
     * 聚合分析
     */
    private SearchRequest buildSearchRequest(SearchParam searchParam){
        SearchRequest searchRequest = new SearchRequest();
        searchRequest.indices(ESConstant.PRODUCT_INDEX);
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //构建具体的检索条件
        BoolQueryBuilder boolQuery= QueryBuilders.boolQuery();
        //关键字检索条件
        if(StringUtils.isNotEmpty(searchParam.getKeyword())){
            boolQuery.must(QueryBuilders.matchQuery("subTitle",searchParam.getKeyword()));
        }
        //类别的检索条件
        if(searchParam.getCateLogId() != null){
            boolQuery.filter(QueryBuilders.termQuery("catalogId",searchParam.getCateLogId()));
        }
        //品牌的检索条件
        if(searchParam.getBrandId() != null && !searchParam.getBrandId().isEmpty()){
            boolQuery.filter(QueryBuilders.termsQuery("brandId",searchParam.getBrandId()));
        }
        //是否有库存的检索条件
        if(searchParam.getHasStock() != null){
            boolQuery.filter(QueryBuilders.termQuery("hasStock",searchParam.getHasStock() == 1));
        }

        //根据价格区间的检索条件
        if(StringUtils.isNotEmpty(searchParam.getSkuPrice())){
            String[] msg = searchParam.getSkuPrice().split("_");
            RangeQueryBuilder skuPrice = QueryBuilders.rangeQuery("skuPrice");
            if(msg.length == 2){
                //200_300
                skuPrice.gte(msg[0]);
                skuPrice.lte(msg[1]);
            }else if(msg.length  == 1){
                //200_ _300
                if(searchParam.getSkuPrice().endsWith("-")){
                    //200_
                    skuPrice.gte(msg[0]);
                }
                if(searchParam.getSkuPrice().startsWith("-")){
                    //_300
                    skuPrice.lte(msg[0]);
                }
            }
            boolQuery.filter(skuPrice);
        }
        //属性的检索 attrs=20_8英寸:10英寸&attrs=19_64gb:10gb
        if(searchParam.getAttrs() != null && !searchParam.getAttrs().isEmpty()){
            for (String attrStr : searchParam.getAttrs()) {
                BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
                String[] attrStrArray = attrStr.split("_");
                //属性的编号
                String attrId = attrStrArray[0];
                //属性的值
                String[] values = attrStrArray[1].split(":");
                boolQueryBuilder.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                boolQueryBuilder.must(QueryBuilders.termsQuery("attrs.attrValue", values));
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", boolQueryBuilder, ScoreMode.None);
                boolQuery.filter(nestedQuery);
            }


        }
        sourceBuilder.query(boolQuery);

        //排序
        if(StringUtils.isNotEmpty(searchParam.getSort())){
            /**
             * sort = saleCount_asc/desc\
             * sort = skuPrice_asc/desc
             * sort = hotScore_asc/desc
             * 排序条件
             */
            String[] sortStr = searchParam.getSort().split("_");
            SortOrder order = sortStr[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC;
            sourceBuilder.sort(sortStr[0], order);
        }
        //处理分页
        if(searchParam.getPageNum() != null){
            //分页处理pageSize = 10
            //pageNum：1  from 0 [0,1,2,3,4,5,6,7,8,9]
            //pageNum：2  from 10 [10,11,12,13,14,15,16,17,18,19]
            sourceBuilder.from((searchParam.getPageNum() - 1) *  ESConstant.PRODUCT_PAGE_SIZE);
            sourceBuilder.size(ESConstant.PRODUCT_PAGE_SIZE);
        }

        //设置高亮
        if(StringUtils.isNotEmpty(searchParam.getKeyword())){
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("subTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            sourceBuilder.highlighter(highlightBuilder);
        }

        //聚合
        //品牌聚合
        TermsAggregationBuilder brandAgg = AggregationBuilders.terms("brand_agg");
        brandAgg.field("brandId");
        brandAgg.size(50);
        //品牌的子聚合
        brandAgg.subAggregation(AggregationBuilders
                .terms("brand_name_agg")
                .field("brandName")
                .size(10)
        );
        brandAgg.subAggregation(AggregationBuilders
                .terms("brand_img_agg")
                .field("brandImg")
                .size(10)
        );
        sourceBuilder.aggregation(brandAgg);
        //分类聚合
        TermsAggregationBuilder catalogAgg = AggregationBuilders.terms("catalog_agg");
        catalogAgg.field("catalogId");
        catalogAgg.size(10);
        //分类的子聚合
        catalogAgg.subAggregation(AggregationBuilders
                .terms("catalog_name_agg")
                .field("catalogName")
                .size(10)
        );
        sourceBuilder.aggregation(catalogAgg);

        //属性聚合
        NestedAggregationBuilder attrAgg = AggregationBuilders.nested("attr_agg","attrs");
        //分类    的子聚合
        attrAgg.subAggregation(AggregationBuilders
                .terms("attr_id_agg")
                .field("attrs.attrId")
                .size(10)
        );
        attrAgg.subAggregation(AggregationBuilders
                .terms("attr_name_agg")
                .field("attrs.attrName")
                .size(10)
        );
        attrAgg.subAggregation(AggregationBuilders
                .terms("attr_value_agg")
                .field("attrs.attrValue")
                .size(10)
        );
        sourceBuilder.aggregation(attrAgg);

        System.out.println("sourceBuilder.toString() = " + sourceBuilder.toString());

        return searchRequest.source(sourceBuilder);
    }
}



























